﻿using System;
using System.Drawing;
using System.Windows.Forms;
using ZXing;    //这个需要外部引用

namespace CustomControl
{
    public partial class QrCodeGenerator : UserControl
    {
        public QrCodeGenerator()
        {
            InitializeComponent();
        }

        private void button17_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(textBox1.Text))
                {
                    MessageBox.Show("请输入内容来生成二维码！");
                }
                GenByZXingNet(textBox1.Text);
                MessageBox.Show("生成二维码成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private Bitmap GenByZXingNet(string msg)
        {
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;  //格式
            writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");  //编码问题
            writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            const int codeSizeInPixels = 350;  ///设置图片长宽
            writer.Options.Height = writer.Options.Width = codeSizeInPixels;
            writer.Options.Margin = 0;   //设置边框
            ZXing.Common.BitMatrix bm = writer.Encode(msg);
            Bitmap img = writer.Write(bm);
            pictureBox1.Image = img;
            return img;
        }
    }
}